//
//  GOauthViewController.swift
//  sinaWeiBoAI
//
//  Created by Z.J on 16/3/21.
//  Copyright © 2016年 Z.J. All rights reserved.
//

import UIKit

import SVProgressHUD

class GOauthViewController: UIViewController {

    // MARK: - view lifecycle
    
    override func loadView() {
         // 在这里设置控制器的view为webView的好处是后面需要添加约束,自己会和屏幕一样大
        view = webview
        
        webview.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavigationItem()
        
        // 使用webView加载登陆界面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webview.loadRequest(request)
        
        
        // 弹出正在加载的提示
        // showWithStatus,需要主动关闭
        SVProgressHUD.showWithStatus("正在加载中", maskType: SVProgressHUDMaskType.None)
        
        // showInfoWithStatus,会自动关闭
        //        SVProgressHUD.showInfoWithStatus("正在加载", maskType: SVProgressHUDMaskType.Clear)
        //        SVProgressHUD.showErrorWithStatus("正在加载")
    }
    
    /// 设置左右边Item
    private func setupNavigationItem()
    {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }

    // MARK: - 懒加载
    private lazy var webview : UIWebView = UIWebView()
}

// MARK: - item点击事件
extension GOauthViewController
{
    // MARK: - 点击的方法
    /// 填充
    @objc private func autoFill() {
        
        let jsCode = "document.getElementById('userId').value='money_av@163.com';document.getElementById('passwd').value='wohenhao'"
        
        // webView执行Js代码
        webview.stringByEvaluatingJavaScriptFromString(jsCode)
        
    }
    /// 取消
    @objc private func close()
    {
        // 关闭控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: -扩展,webView代理方法
extension GOauthViewController:UIWebViewDelegate
{
    func webViewDidFinishLoad(webView: UIWebView) {
        
        // 关闭提示
        SVProgressHUD.dismiss()
    }
    
    // 每次请求都会调用此方法,是否加载某个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {// true 表示加载这个地址,false就不加载
        /// 请求的URL
        let urlString = request.URL!.absoluteString
        
        // 当点击了取消后授权后都会加载授权回调地址,所以判断如果是授权回调地址就表示点击的是 取消 或 授权
        // 不是授权回调地址,让他加载

        // 判断网址是否已回调网址开头
        if !urlString.hasPrefix(redirect_uri)
        {
  
            return true
        }else
        {   // 加载的授权回调地址,说明点击的是 取消 或 授权
            // 获取参数
            // query: get请求?后面的参数 
            let query = request.URL?.query
            // 判断query是否以code=开头
            let codeStr = "code="
            if query!.hasPrefix(codeStr)
            {
                // 如果匹配,证明点击的是授权,截取后面的code
                let nsquery = query! as NSString
                let code = nsquery.substringFromIndex(codeStr.characters.count)
                // 获取数据
                GUserAccountViewModel.sharedinstance.loadAccessToken(code, completion: { (error) -> () in
                    if error != nil
                    {// 证明获取数据失败
                        print("error : \(error)")
                        SVProgressHUD.showErrorWithStatus("获取AccessToken失败")
                        // 延迟1秒再关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                        return
                    }
                    // 没有错误
                    // 关闭控制器
                    print("没有错误关闭控制器")
                    self.close()
                })

                
            }else
            {
                // 点击的是取消,关闭界面
                close()
            }
            return false
        }
        
    }
    
   
    

}